import json
import os


def save_json(result, path, sort_keys=False):
    with open(path, 'w', encoding='utf8') as f:
        json.dump(result, f, sort_keys=sort_keys, indent=4)


def load_json(path, default: dict = None):
    if not default:
        default = {}

    # 分离出文件路径中的目录部分
    directory = os.path.dirname(path)

    # 如果目录不存在，则创建它
    if not os.path.exists(directory):
        os.makedirs(directory)

    if not os.path.exists(path):
        with open(path, 'w', encoding='utf8') as fp:
            json.dump(default, fp, sort_keys=False, indent=4)
            return default

    with open(path, 'r', encoding='utf8') as fp:
        result = json.load(fp)

    if not result:
        if default:
            save_json(default, path)
            return default
    return result

def convert_to_type(num):
    # 如果参数是浮点数，并且小数点后面有非零数字，则float,否则int
    try:
        if isinstance(num, float) and num != int(num):
            return float(num)
        else:
            try:
                return int(num)
            except:
                return num
    except:
        return num